﻿using System;
using System.IO;

namespace Com.OpenCode.Framework.Core
{
    /// <summary>
    ///     插件树。
    /// </summary>
    public static class AddinTree
    {
        /// <summary>
        ///     插件树启动位置。
        /// </summary>
        public static string AddInBasePath { get; set; }

        public static Addins Addins { get; private set; }

        public static void Start()
        {
            Addins = new Addins();
            if (string.IsNullOrEmpty(AddInBasePath))
            {
                throw new Exception("插件启动路径不能为空。");
            }
            string[] files = Directory.GetFiles(AddInBasePath, "*.addin", SearchOption.AllDirectories);
            if (files == null || files.Length == 0)
            {
                throw new Exception(string.Format("在启动路径{0}下未找到插件配置文件。", AddInBasePath));
            }
            foreach (string file in files)
            {
                Addin addin = new Addin();
                addin.Load(file);
                addin.InitCore();
                Addins.Add(addin);
            }
            Addins.Sort();
            Addins.Genetic();
            for (int i = 0; i < Addins.Count; i++)
            {
                Addin addin = Addins.Get(i);
                if (addin.StartLevel != -1)
                {
                    addin.Start();
                }
            }
        }

        public static void Stop()
        {
            for (int i = Addins.Count - 1; i > 0; i--)
            {
                Addins.Get(i).Stop();
            }
        }

        public static void Ban()
        {
            for (int i = Addins.Count - 1; i > 0; i--)
            {
                Addins.Get(i).Ban();
            }
        }
    }
}